

import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, FlatList, RefreshControl, Modal, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';
import ApprovalItem from './components/ApprovalItem';
import FilterDropdown from './components/FilterDropdown';

interface ApprovalRecord {
  id: string;
  title: string;
  applicant: string;
  submitTime: string;
  processId: string;
  status: 'approved' | 'rejected' | 'transferred';
  processTime: string;
  processResult: string;
}

const ApprovedByMeScreen = () => {
  const router = useRouter();
  const [searchText, setSearchText] = useState('');
  const [isFilterDropdownVisible, setIsFilterDropdownVisible] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [approvalRecords, setApprovalRecords] = useState<ApprovalRecord[]>([]);
  const [filteredRecords, setFilteredRecords] = useState<ApprovalRecord[]>([]);
  const [selectedFilters, setSelectedFilters] = useState({
    all: true,
    approved: true,
    rejected: true,
    transferred: true,
  });

  // 模拟数据
  const mockApprovalData: ApprovalRecord[] = [
    {
      id: '1',
      title: '员工请假申请',
      applicant: '李小明',
      submitTime: '2024-01-15 14:30',
      processId: 'proc-001',
      status: 'approved',
      processTime: '2024-01-15 15:45',
      processResult: '通过',
    },
    {
      id: '2',
      title: '采购申请单',
      applicant: '王采购',
      submitTime: '2024-01-14 09:15',
      processId: 'proc-002',
      status: 'rejected',
      processTime: '2024-01-14 10:20',
      processResult: '驳回',
    },
    {
      id: '3',
      title: '差旅报销申请',
      applicant: '赵销售',
      submitTime: '2024-01-13 16:20',
      processId: 'proc-003',
      status: 'transferred',
      processTime: '2024-01-13 17:10',
      processResult: '转办',
    },
    {
      id: '4',
      title: '加班申请',
      applicant: '孙开发',
      submitTime: '2024-01-12 18:45',
      processId: 'proc-004',
      status: 'approved',
      processTime: '2024-01-12 19:30',
      processResult: '通过',
    },
    {
      id: '5',
      title: '办公用品申请',
      applicant: '刘行政',
      submitTime: '2024-01-11 11:20',
      processId: 'proc-005',
      status: 'approved',
      processTime: '2024-01-11 13:15',
      processResult: '通过',
    },
  ];

  useEffect(() => {
    loadApprovalData();
  }, []);

  useEffect(() => {
    filterApprovalRecords();
  }, [approvalRecords, searchText, selectedFilters]);

  const loadApprovalData = async () => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      setApprovalRecords(mockApprovalData);
    } catch (error) {
      Alert.alert('错误', '加载数据失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const filterApprovalRecords = () => {
    let filtered = approvalRecords;

    // 搜索过滤
    if (searchText.trim()) {
      const searchLower = searchText.toLowerCase();
      filtered = filtered.filter(record =>
        record.title.toLowerCase().includes(searchLower) ||
        record.applicant.toLowerCase().includes(searchLower)
      );
    }

    // 状态过滤
    if (!selectedFilters.all) {
      filtered = filtered.filter(record => {
        switch (record.status) {
          case 'approved':
            return selectedFilters.approved;
          case 'rejected':
            return selectedFilters.rejected;
          case 'transferred':
            return selectedFilters.transferred;
          default:
            return false;
        }
      });
    }

    setFilteredRecords(filtered);
  };

  const handleRefresh = async () => {
    setIsRefreshing(true);
    try {
      await loadApprovalData();
    } finally {
      setIsRefreshing(false);
    }
  };

  const handleLoadMore = async () => {
    if (isLoadingMore) return;
    
    setIsLoadingMore(true);
    try {
      // 模拟加载更多数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      // 这里可以添加更多数据到列表
    } finally {
      setIsLoadingMore(false);
    }
  };

  const handleFilterPress = () => {
    setIsFilterDropdownVisible(true);
  };

  const handleFilterApply = (filters: typeof selectedFilters) => {
    setSelectedFilters(filters);
    setIsFilterDropdownVisible(false);
  };

  const handleApprovalItemPress = (processId: string) => {
    router.push(`/p-approval_detail?processInstanceId=${processId}`);
  };

  const renderApprovalItem = ({ item }: { item: ApprovalRecord }) => (
    <ApprovalItem
      record={item}
      onPress={() => handleApprovalItemPress(item.processId)}
    />
  );

  const renderHeader = () => (
    <View style={styles.headerContainer}>
      <View style={styles.titleRow}>
        <LinearGradient
          colors={['#6366f1', '#8b5cf6']}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.titleGradient}
        >
          <Text style={styles.pageTitle}>我已审批</Text>
        </LinearGradient>
        
        <TouchableOpacity
          style={styles.filterButton}
          onPress={handleFilterPress}
          activeOpacity={0.7}
        >
          <FontAwesome6 name="filter" size={14} color="#9ca3af" />
          <Text style={styles.filterButtonText}>筛选</Text>
          <FontAwesome6 name="chevron-down" size={12} color="#9ca3af" />
        </TouchableOpacity>
      </View>

      <View style={styles.searchContainer}>
        <FontAwesome6 name="magnifying-glass" size={16} color="#9ca3af" style={styles.searchIcon} />
        <TextInput
          style={styles.searchInput}
          placeholder="搜索审批标题、发起人..."
          placeholderTextColor="#9ca3af"
          value={searchText}
          onChangeText={setSearchText}
        />
      </View>
    </View>
  );

  const renderFooter = () => {
    if (isLoading) return null;
    
    return (
      <View style={styles.footerContainer}>
        <TouchableOpacity
          style={styles.loadMoreButton}
          onPress={handleLoadMore}
          activeOpacity={0.7}
          disabled={isLoadingMore}
        >
          {isLoadingMore ? (
            <View style={styles.loadingSpinner} />
          ) : (
            <Text style={styles.loadMoreButtonText}>加载更多</Text>
          )}
        </TouchableOpacity>
      </View>
    );
  };

  const renderEmptyState = () => {
    if (isLoading) {
      return (
        <View style={styles.emptyStateContainer}>
          <View style={styles.loadingSpinner} />
          <Text style={styles.emptyStateText}>正在加载...</Text>
        </View>
      );
    }

    return (
      <View style={styles.emptyStateContainer}>
        <FontAwesome6 name="clipboard-list" size={64} color="#4b5563" style={styles.emptyStateIcon} />
        <Text style={styles.emptyStateTitle}>暂无已审批记录</Text>
        <Text style={styles.emptyStateSubtitle}>您还没有处理过任何审批</Text>
      </View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={filteredRecords}
        renderItem={renderApprovalItem}
        keyExtractor={(item) => item.id}
        ListHeaderComponent={renderHeader}
        ListFooterComponent={renderFooter}
        ListEmptyComponent={renderEmptyState}
        contentContainerStyle={styles.listContainer}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl
            refreshing={isRefreshing}
            onRefresh={handleRefresh}
            tintColor="#6366f1"
            colors={['#6366f1']}
          />
        }
      />

      <FilterDropdown
        visible={isFilterDropdownVisible}
        selectedFilters={selectedFilters}
        onApply={handleFilterApply}
        onClose={() => setIsFilterDropdownVisible(false)}
      />
    </SafeAreaView>
  );
};

export default ApprovedByMeScreen;

